package br.com.pd.messaging;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import br.com.util.PropertiesLoader;

public class RequestReceiver  extends Thread implements Subject {

	private int port;

	
	private List<Listener> listeners;
	
	private Queue<String> queueReceive;
	
	public RequestReceiver(int port){
		this.queueReceive = new ConcurrentLinkedQueue<String>();
		this.listeners = new ArrayList<Listener>();
		this.port = port;
	}

	public String receive() {
		return queueReceive.poll();
	}
	
	private void receiveFromServer() {
		
		ServerSocket welcomeSocket = null;
		Socket connectionSocket = null;
		BufferedReader inFromClient = null;
		try {
			welcomeSocket = new ServerSocket(port);
			while (true) {
				String clientSentence = "";
				String tmp = "";
				System.out.println("Socket Receiver listening ..");
				connectionSocket = welcomeSocket.accept();
				inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
				while ((tmp = inFromClient.readLine()) != null) {
					clientSentence += tmp + "\n";
				}
				System.out.println("mensagem recebida ---- >");
				System.out.println(clientSentence);
				this.queueReceive.add(clientSentence);
				this.update(); // dispara evento avisando que chegou mensagem
				connectionSocket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// Encerra o ServerSocket
				welcomeSocket.close();
				
			} catch (IOException e) {
			}
		}
		
	}
	
	@Override
	public void run(){
		this.receiveFromServer();
	}
	
	public void update() {
		for (Listener l : this.listeners) {
			l.update();
		}
	}
	
	@Override
	public void addObserver(Listener o) {
		this.listeners.add(o);
	}

	@Override
	public void removeObserver(Listener o) {
		this.listeners.remove(o);
	}

	public static void main(String[] args) {
		RequestReceiver c = new RequestReceiver(Integer.parseInt(PropertiesLoader.getInstance().getPropertie(PropertiesLoader.PORT_FACTORY_RECEIVER)));
		c.run();
	}
}
